package com.loadmore.stepcount

import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.IBinder
import android.os.PowerManager
import com.loadmore.common.constants.Api
import com.loadmore.common.log.LogUtil
import com.loadmore.common.model.BaseResponse
import com.loadmore.common.net.Request
import com.loadmore.common.net.impl.JsonCallback
import com.loadmore.common.variables.Variables
import com.lzy.okgo.model.Response
import java.util.*


class StepCountService : Service() {


    var stepCount = 0
    var wakeLock:PowerManager.WakeLock? = null
    lateinit var token: String
    override fun onCreate() {
        super.onCreate()
        val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
        wakeLock = pm!!.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, StepCountService::class.java!!.name)
        wakeLock?.acquire()
        token = Variables.token!!
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        sensorManager.registerListener(object : SensorEventListener {
            override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
            }

            override fun onSensorChanged(sensorEvent: SensorEvent?) {
                if (sensorEvent?.sensor?.type == Sensor.TYPE_STEP_COUNTER) {
                    LogUtil.d("onSensorChanged " + sensorEvent.values[0])
                    stepCount++
                }
            }

        }, sensor, 60 * 1000)

    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            AlarmActions.upload_step_count->{


                //限制在 23:50-00:00 之间不上传数据，避免冲突
                if(inTimeZone())
                    uploadStep()

            }
            AlarmActions.zero_alarm -> {
                uploadStep()
                stepCount = 0
            }
        }
        return START_STICKY
    }

    private fun inTimeZone():Boolean {
        var calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY,23)
        calendar.set(Calendar.MINUTE,50)
        calendar.set(Calendar.SECOND,0)
        calendar.set(Calendar.MILLISECOND,0)
        var current = System.currentTimeMillis()
        //时间在今天23:50 至 第二天00:10 之间 为不上传时间段
        if (current > calendar.timeInMillis && current <calendar.timeInMillis+1000*60*20) {
            return false
        }
        return true
    }

    private fun uploadStep() {
        Request.post(Api.step_count,
                hashMapOf<String, Any>("token" to token, "step" to stepCount),
                object : JsonCallback<BaseResponse<Step>>() {
                    override fun onSuccess(response: Response<BaseResponse<Step>>?) {
                        val step = response?.body()?.data
                        if(step != null && step.step> stepCount) {
                            stepCount = step.step
                            LogUtil.d("与服务器数据同步成功!")
                        }
                    }

                    override fun onError(response: Response<BaseResponse<Step>>?) {
                        super.onError(response)
                    }
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (wakeLock != null) {
            wakeLock?.release()
            wakeLock = null
        }
    }

}
